package com.wooboo.server.ext.service;

import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.alibaba.druid.support.json.JSONUtils;
import com.wooboo.dsp.redis.util.RedisClient;
import com.wooboo.server.ext.ApiError;
import com.wooboo.server.ext.constants.StatusEnums;
import com.wooboo.server.ext.data.AdversitingRedis;
import com.wooboo.server.ext.data.GlobalEnums;
import com.wooboo.server.ext.dbutil.JdbcTemplate;
import com.wooboo.server.ext.dbutil.Sql;
import com.wooboo.server.ext.util.DateUtil;

public class BillingService {

	private JdbcTemplate jdbcTemplate = new JdbcTemplate();

	private String sing = ":";

	/**
	 * 
	 * @Description: 获取可以
	 * @param @return
	 * @return String
	 * @throws @author jj
	 * @date 2015-8-31
	 */
	public String getKey(AdversitingRedis adversitingRedis) {
		StringBuilder key = new StringBuilder();
		key.append(adversitingRedis.getPlan_id()).append(sing)
				.append(adversitingRedis.getGroup_id()).append(sing)
				.append(adversitingRedis.getId());
		return key.toString();
	}

	public String getSql() {
		String currDate = DateUtil.getFormatDate(new Date(), "yyyy-MM-dd");

		StringBuilder sb = new StringBuilder();
		sb.append(" select a.id,c.platform_limit as channel_id,a.plan_id,a.group_id,a.`owner`, ")
				.append(" e.width,e.height,e.stuff_url,e.land_url, ")
				.append(" CASE e.type WHEN '1' THEN 'b' WHEN '2' THEN 'v' ELSE 's' END AS type , ")
				.append(" b.total_budget_rmb,b.total_budget_flow,b.billing_type, ")
				.append(" c.ad_type_limit ,c.area_limit, c.time_limit, c.app_type_limit, ")
				.append(" c.operator_limit, c.network_limit, ")
				.append(" c.device_os_limit, c.device_brand_limit, ")
				.append(" c.device_attr_limit, a.bid_price,a.bid_flow, ")
				.append(" c.screen_position_limit, c.show_way_limit, ")
				.append(" c.group_budget_rmb ,c.group_budget_flow,c.deliver_speed, ")
				.append(" f.money as plan_cost_rmb,g.money as group_cost_rmb,h.money as idea_cost_rmb ")
				.append(" from admanage_idea a ")
				.append(" left join admanage_plan b on b.id = a.plan_id ")
				.append(" left join admanage_group c on c.id = a.group_id ")
				.append(" left join channel_info d on d.id = c.platform_limit ")
				.append(" left join admanage_stuff e on e.idea_id = a.id ")
				.append(" left join rep_plan_date f on f.plan_id = a.plan_id ")
				.append(" left join rep_group_date g on g.group_id = a.group_id ")
				.append(" left join rep_idea_date h on h.idea_id = a.id ")
				// .append(" where a.id = ?")
				.append(" where 1 = 1 ")
				.append(" and b.start_date <= '"
						+ currDate
						+ " 00:00:00' and ADDDATE(b.end_date,INTERVAL 1 DAY) >='"
						+ currDate + " 23:59:59' ")
				.append(" and c.start_date <= '"
						+ currDate
						+ " 00:00:00' and ADDDATE(c.end_date,INTERVAL 1 DAY) >='"
						+ currDate + " 23:59:59' ")
				.append(" and a.is_valid = 1 and b.is_valid = 1 and c.is_valid = 1 ")
				.append(" and a.is_close = 1 and b.is_close = 1 and c.is_close = 1 ")
				.append(" and a.status = "+StatusEnums.PASS.getId());
		return sb.toString();
	}

	public void bll() {

		String preSql = getSql();
		System.out.println("sql===" + preSql.toString());

		List<AdversitingRedis> adversitingRedisList = null;
		try {
			Sql sql = new Sql(preSql.toString());
			adversitingRedisList = jdbcTemplate.queryForList(sql,
					AdversitingRedis.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (adversitingRedisList == null || adversitingRedisList.size() == 0) {
			return;
		}

		for (AdversitingRedis ad : adversitingRedisList) {
			String key = getKey(ad);

			StringBuilder value = new StringBuilder();
			value.append("{");
			value.append("\"id\":" + ad.getId() + ",");

			value.append("\"plan_id\":" + ad.getPlan_id() + ",");

			value.append("\"group_id\":" + ad.getGroup_id() + ",");

			value.append("\"total_budget_rmb\":" + ad.getTotal_budget_rmb()
					+ ",");
			value.append("\"total_cost_rmb\":" + ad.getTotal_cost_rmb()
					+ ",");	
		
			value.append("\"group_budget_rmb\":" + ad.getGroup_budget_rmb()
					+ ",");
			
			value.append("\"group_cost_rmb\":" + ad.getGroup_cost_rmb()
					+ ",");
			value.append("\"idea_cost_rmb\":" + ad.getIdea_cost_rmb()
					+ ",");
			
			value.append("\"billing_type\":" + ad.getBilling_type() + ",");

			value.append("\"bid_price\":" + ad.getBid_price() + ",");

			value.append("\"bid_flow\":" + ad.getBid_flow());

			value.append("}");

			RedisClient client = RedisClient.getRedisClient();
			client.set(key.toString(), value.toString());

		}

	}

	/**
	 * 
	 * @Description: 地域定向
	 * @param @param lct
	 * @param @return
	 * @return String
	 * @throws @author jj
	 * @date 2015-9-1
	 */
	private String areaLimit(String lct) {
		StringBuffer value = new StringBuffer();
		// 区域定向
		if (lct == null || "0".equals(lct)) {
			value.append("\"area_limit\":[\"all\"],");

		} else {
			Map aere = (Map) JSONUtils.parse(lct);
			Map areaMap = (Map) aere.get("area");

			Iterator iterator = areaMap.values().iterator();
			value.append("\"area_limit\":[");
			int i = 0;
			while (iterator.hasNext()) {
				// 地区id
				String tempAreaName = (String) iterator.next();

				if (i == 0) {
					value.append("\"" + tempAreaName + "\"");
				} else {
					value.append(",\"" + tempAreaName + "\"");
				}
				i++;
			}
			value.append("],");
		}
		return value.toString();
	}

	/**
	 * 
	 * @Description: 时间定向
	 * @param @param t
	 * @param @return
	 * @return String
	 * @throws @author jj
	 * @date 2015-9-1
	 */
	private String timeLimit(String t) {
		StringBuffer value = new StringBuffer();
		// 区域定向
		if (t == null || "0".equals(t)) {
			value.append("\"time_limit\":[\"all\"],");

		} else {
			Map time = (Map) JSONUtils.parse(t);
			Set ks = time.keySet();
			int l = ks.size();
			// key
			Iterator iterator = ks.iterator();
			value.append("\"time_limit\":{");
			int i = 0;
			while (iterator.hasNext()) {
				// 周
				String week = (String) iterator.next();
				value.append("\"" + week + "\":");
				// 值
				String weekValue = (String) time.get(week);
				// 将值拆分
				String[] valueArr = weekValue.split("\\|");
				Set weekSet = new HashSet();
				for (int k = 0; k < valueArr.length; k++) {
					weekSet.add(valueArr[k]);
				}
				value.append("\"");
				// 循环24小时
				for (int j = 0; j < 24; j++) {
					if (weekSet.contains(j + "")) {
						value.append("1");
					} else {
						value.append("0");
					}
				}
				value.append("\"");
				if (!((l - 1) == i)) {
					value.append(",");
				}
				i++;
			}

			value.append("},");
		}
		return value.toString();
	}

	/**
	 * 
	 * @Description: app类型
	 * @param @param at
	 * @param @param code
	 * @param @return
	 * @return String
	 * @throws @author jj
	 * @date 2015-9-1
	 */
	private String appTypeLimit(String at, Long code) {
		StringBuffer value = new StringBuffer();
		// 全部
		if (at == null || "".equals(at) || "0".equals(at)) {
			value.append("\"app_type_limit\":[\"all\"],");

		} else {
			Map atMap = (Map) JSONUtils.parse(at);
			Iterator atIterator = atMap.keySet().iterator();
			String tempAt = "";
			while (atIterator.hasNext()) {
				String key = (String) atIterator.next();
				if ("".equals(tempAt)) {
					tempAt = key;
				} else {
					tempAt = tempAt + "," + key;
				}
			}
			// 根据已选择的dsp的APP分类和平台code查询对应平台的app分类
			String sql = "select a.pater_id as platformAppCode from rmc_platform p "
					+ " inner join umc_apptype a ON p.id = a.channel "
					+ " inner join rmc_app_relation r on r.platformApp = a.id "
					+ " where r.itemApp in ("
					+ tempAt
					+ ") and p.`code`='"
					+ code + "'";
			// List list = jdbcTemplate.queryForList(sql);
			List list = null;
			if (list != null && list.size() > 0) {
				value.append("\"app_type_limit\":[");
				for (int i = 0; i < list.size(); i++) {
					Map appMap = (Map) list.get(i);
					if (i == 0) {
						value.append("\"" + appMap.get("platformAppCode")
								+ "\"");
					} else {
						value.append(",\"" + appMap.get("platformAppCode")
								+ "\"");
					}
				}
				value.append("],");
			} else {
				value.append("\"app_type_limit\":[\"all\"],");
			}
		}
		return value.toString();
	}

	/**
	 * 
	 * @Description: 运营商定向
	 * @param @param op
	 * @param @return
	 * @return String
	 * @throws @author jj
	 * @date 2015-9-1
	 */
	private String operatorLimit(String op) {
		StringBuffer value = new StringBuffer();

		if (op == null || "0".equals(op) || "".equals(op)) {
			value.append("\"operator_limit\":[\"all\"],");

		} else {
			// 0:移动 1：联通 2：电信 3：其他
			// //网络运营商定向：0=全选，其他：1=移动，2=联通，3=电信，4=其他，可多选
			value.append("\"operator_limit\":[");
			String[] opArr = op.split(",");
			for (int i = 0; i < opArr.length; i++) {
				int opt = Integer.parseInt(opArr[i]);

				if (i == 0) {
					value.append("\"" + (opt - 1) + "\"");
				} else {
					value.append(",\"" + (opt - 1) + "\"");
				}
			}
			value.append("],");
		}
		return value.toString();
	}

	/**
	 * 
	 * @Description: 运营商定向
	 * @param @param op
	 * @param @return
	 * @return String
	 * @throws @author jj
	 * @date 2015-9-1
	 */
	private String networkLimit(String nk) {
		StringBuffer value = new StringBuffer();

		if (nk == null || "0".equals(nk)) {
			value.append("\"network_limit\":[\"all\"],");

		} else {
			// 网络类型 0:其他 1：wifi 2：2G 3：3G 4：4G ，全部默认all
			// //移动网络定向：0=全选，其他：1=2G，2=3G，3=4G，可多选
			value.append("\"network_limit\":[");
			String[] nkArr = nk.split(",");
			for (int i = 0; i < nkArr.length; i++) {
				if (i == 0) {
					value.append("\"" + getNetworkLimit(nkArr[i]) + "\"");
				} else {
					value.append(",\"" + getNetworkLimit(nkArr[i]) + "\"");
				}
			}
			value.append("],");
		}
		return value.toString();
	}

	private String getNetworkLimit(String nk) {

		if ("1".equals(nk)) {
			return "2";
		} else if ("2".equals(nk)) {
			return "3";
		} else if ("3".equals(nk)) {
			return "4";
		} else if ("4".equals(nk)) {
			return "1";
		}

		return "0";
	}

	/**
	 * 
	 * @Description: 操作系统
	 * @param @param os
	 * @param @return
	 * @return String
	 * @throws @author jj
	 * @date 2015-9-1
	 */
	private String device_os_limit(String os) {
		StringBuffer value = new StringBuffer();
		// 操作系统 0:其他 1:ios 2:android 3:windowsphone ，默认全部all
		// ////移动设备操作系统定向：0=不限，其他则存json串

		if (os == null || "0".equals(os)) {
			value.append("\"device_os_limit\":[\"all\"],");

		} else {
			// 网络类型 0:其他 1：wifi 2：2G 3：3G 4：4G ，全部默认all
			// //移动网络定向：0=全选，其他：1=2G，2=3G，3=4G，可多选

			Map osMap = (Map) JSONUtils.parse(os);
			int l = osMap.keySet().size();
			// key
			Iterator iterator = osMap.keySet().iterator();
			// 操作系统 0:其他 1:ios 2:android 3:windowsphone ，默认全部all
			value.append("\"device_os_limit\":{");
			int k = 0;
			while (iterator.hasNext()) {

				String osKey = (String) iterator.next();
				if (osKey.equals("ios")) {
					value.append("\"1\":");
				} else if (osKey.equals("android")) {
					value.append("\"2\":");
				} else if (osKey.equals("windowsphone")) {
					value.append("\"3\":");
				} else {
					value.append("\"0\":");
				}

				Object tvMap = (Object) osMap.get(osKey);
				if (tvMap instanceof String) {
					value.append("[\"all\"]");
				} else {
					Map vMap = (Map) osMap.get(osKey);
					Iterator viterator = vMap.values().iterator();
					value.append("[");
					int i = 0;
					while (viterator.hasNext()) {
						String vv = (String) viterator.next();
						if (i == 0) {
							value.append("\"" + vv + "\"");
						} else {
							value.append(",\"" + vv + "\"");
						}
						i++;
					}
					value.append("]");
				}
				if (!(k == (l - 1))) {
					value.append(",");
				}
				k++;
			}
			value.append("},");
		}
		return value.toString();
	}

	/**
	 * 
	 * @Description: TODO
	 * @param @param dt
	 * @param @return
	 * @return String
	 * @throws @author jj
	 * @date 2015-9-1
	 */
	private String deviceBrandLimit(String dt) {
		StringBuffer value = new StringBuffer();

		if (dt == null || "0".equals(dt)) {
			value.append("\"device_brand_limit\":[\"all\"],");

		} else {
			Map dtMap = (Map) JSONUtils.parse(dt);
			Set st = dtMap.keySet();
			int l = st.size();
			// key
			Iterator iterator = st.iterator();
			value.append("\"device_brand_limit\":{");
			int i = 0;
			while (iterator.hasNext()) {
				String key = (String) iterator.next();

				if (i == 0) {
					if ("cellphone".equals(key)) {
						value.append("\"" + 1 + "\":");
					}
					if ("pad".equals(key)) {
						value.append("\"" + 0 + "\":");
					}
				} else {
					if ("cellphone".equals(key)) {
						value.append(",\"" + 1 + "\":");
					}
					if ("pad".equals(key)) {
						value.append(",\"" + 0 + "\":");
					}
				}
				Object vvmap = (Object) dtMap.get(key);
				if (vvmap instanceof String) {
					value.append("[\"all\"]");

				} else {
					Map vmap = (Map) dtMap.get(key);
					Iterator vi = vmap.values().iterator();
					int k = 0;
					value.append("[");
					while (vi.hasNext()) {
						String vv = (String) vi.next();
						if (k == 0) {
							value.append("\"" + (vv) + "\"");
						} else {
							value.append(",\"" + (vv) + "\"");
						}
						k++;
					}
					value.append("]");
				}
				i++;
			}
			value.append("},");
		}
		return value.toString();
	}

	private String deviceAttrLimit(String ds) {

		StringBuffer value = new StringBuffer();
		if ("0".equals(ds) || ds == null) {
			value.append("\"ds\":[\"all\"],");
			value.append("\"dp\":[\"all\"],");
		} else {

			Map dsMap = (Map) JSONUtils.parse(ds);
			Object sizeMap = dsMap.get("size");
			Object priceMap = dsMap.get("price");
			if (sizeMap instanceof String || sizeMap == null) {
				value.append("\"ds\":[\"all\"],");
			} else {
				Map sMap = (Map) sizeMap;
				Iterator si = sMap.keySet().iterator();
				value.append("\"ds\":[");
				int i = 0;
				while (si.hasNext()) {
					String siv = (String) si.next();
					if (i == 0) {
						value.append("\"" + this.getCode(siv) + "\"");
					} else {
						value.append(",\"" + this.getCode(siv) + "\"");
					}
					i++;
				}
				value.append("],");
			}
			if (priceMap instanceof String || priceMap == null) {
				value.append("\"dp\":[\"all\"],");
			} else {
				Map pMap = (Map) priceMap;
				value.append("\"dp\":[");
				Iterator pi = pMap.keySet().iterator();

				int i = 0;
				while (pi.hasNext()) {
					String piv = (String) pi.next();
					if (i == 0) {
						value.append("\"" + this.getCode(piv) + "\"");
					} else {
						value.append(",\"" + this.getCode(piv) + "\"");
					}
					i++;
				}
				value.append("],");
			}
		}
		return value.toString();
	}

	/**
	 * 
	 * @Description: 视频类型创意的展示方式,字符串数组类型(1：线性播放 2：悬浮 3: 暂停 4：全屏(包括开屏，插屏)
	 *               5：固定)，默认全部all
	 * @param @param sp
	 * @param @return
	 * @return String
	 * @throws @author duanwei
	 * @date 2016-2-3
	 */
	private String showWayLimit(String ds) {
		StringBuffer value = new StringBuffer();

		if ("0".equals(ds) || ds == null) {
			value.append("\"show_way_limit\":[\"all\"],");
		} else {

			value.append("\"show_way_limit\":{");

			Map dsMap = (Map) JSONUtils.parse(ds);
			Object xx = dsMap.get("xx");
			Object xf = dsMap.get("xf");
			Object zt = dsMap.get("zt");
			Object qp = dsMap.get("qp");
			Object gd = dsMap.get("gd");
			if (xx instanceof String || xx == null) {
				value.append("\"1\":[\"all\"],");
			} else {
				Map sMap = (Map) xx;
				Iterator si = sMap.keySet().iterator();
				value.append("\"1\":[");
				int i = 0;
				while (si.hasNext()) {
					String siv = (String) si.next();
					if (i == 0) {
						value.append("\"" + siv + "\"");
					} else {
						value.append(",\"" + siv + "\"");
					}
					i++;
				}
				value.append("],");
			}

			if (xf instanceof String || xf == null) {
				value.append("\"2\":[\"all\"],");
			} else {
				Map pMap = (Map) xf;
				value.append("\"2\":[");
				Iterator pi = pMap.keySet().iterator();

				int i = 0;
				while (pi.hasNext()) {
					String piv = (String) pi.next();
					if (i == 0) {
						value.append("\"" + piv + "\"");
					} else {
						value.append(",\"" + piv + "\"");
					}
					i++;
				}
				value.append("],");
			}

			if (zt instanceof String || zt == null) {
				value.append("\"3\":[\"all\"],");
			} else {
				Map pMap = (Map) zt;
				value.append("\"3\":[");
				Iterator pi = pMap.keySet().iterator();

				int i = 0;
				while (pi.hasNext()) {
					String piv = (String) pi.next();
					if (i == 0) {
						value.append("\"" + piv + "\"");
					} else {
						value.append(",\"" + piv + "\"");
					}
					i++;
				}
				value.append("],");
			}

			if (qp instanceof String || qp == null) {
				value.append("\"4\":[\"all\"],");
			} else {
				Map pMap = (Map) qp;
				value.append("\"4\":[");
				Iterator pi = pMap.keySet().iterator();

				int i = 0;
				while (pi.hasNext()) {
					String piv = (String) pi.next();
					if (i == 0) {
						value.append("\"" + piv + "\"");
					} else {
						value.append(",\"" + piv + "\"");
					}
					i++;
				}
				value.append("],");
			}

			if (qp instanceof String || qp == null) {
				value.append("\"5\":[\"all\"],");
			} else {
				Map pMap = (Map) gd;
				value.append("\"5\":[");
				Iterator pi = pMap.keySet().iterator();

				int i = 0;
				while (pi.hasNext()) {
					String piv = (String) pi.next();
					if (i == 0) {
						value.append("\"" + piv + "\"");
					} else {
						value.append(",\"" + piv + "\"");
					}
					i++;
				}
				value.append("],");
			}
			String delValue = value.substring(0, value.length() - 1);
			value = new StringBuffer(delValue);

			value.append("},");
		}
		return value.toString();
	}

	/**
	 * 
	 * @Description: 广告屏次，字符串数组类型(1: 首屏 2：次屏 3：其他屏)，默认全部all
	 * @param @param sp
	 * @param @return
	 * @return String
	 * @throws @author duanwei
	 * @date 2016-2-3
	 */
	private String screenPositionLimit(String sp) {
		StringBuffer value = new StringBuffer();

		if (sp == null || "0".equals(sp) || "".equals(sp)) {
			value.append("\"screen_position_limit\":[\"all\"],");

		} else {
			// 0:移动 1：联通 2：电信 3：其他
			// //网络运营商定向：0=全选，其他：1=移动，2=联通，3=电信，4=其他，可多选
			value.append("\"screen_position_limit\":[");
			String[] opArr = sp.split(",");
			for (int i = 0; i < opArr.length; i++) {
				int opt = Integer.parseInt(opArr[i]);

				if (i == 0) {
					value.append("\"" + (opt - 1) + "\"");
				} else {
					value.append(",\"" + (opt - 1) + "\"");
				}
			}
			value.append("],");
		}
		return value.toString();
	}

	private String getCode(String id) {

		int code = -1;
		try {
			String sql = "select id,code,item_name from global_enums where id="
					+ id;
			GlobalEnums globalEnums = jdbcTemplate.findObject(new Sql(sql),
					GlobalEnums.class);
			if (globalEnums != null && globalEnums.getCode() != null) {
				code = globalEnums.getCode();
			}
		} catch (ApiError e) {
			e.printStackTrace();
		}
		return code + "";
	}

	public static void main(String[] args) {
		BillingService push = new BillingService();
		//push.putIdeaToReadis(2151L);
	}

}
